package jp.reflexworks.gae.util;

import java.text.DecimalFormat;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class KeyUtils {

	protected String BASE_KEY_KIND;
	protected String BASE_KEY_NAME;
	protected String PREFIX = "K";

	public KeyUtils(Class basekind) {
		this(basekind, basekind.getSimpleName());
	}

	public KeyUtils(Class basekind, String baseName) {
		this(basekind, baseName, null);
	}

	public KeyUtils(Class basekind, String baseName, String prefix) {
		BASE_KEY_KIND = basekind.getSimpleName();
		BASE_KEY_NAME = baseName;
		if (prefix != null) {
			PREFIX = prefix;
		}
	}

	public KeyFactory.Builder getBaseKeyBuilder() {
		return new KeyFactory.Builder(BASE_KEY_KIND, BASE_KEY_NAME);
	}

	public String getRecordKeyName(long id) {
		DecimalFormat idformat = new DecimalFormat("00000000000000000000");
		return "ID" + idformat.format(id);
	}

	public Key getRecordKey(Class kind, long id) {
		return getBaseKeyBuilder().addChild(kind.getSimpleName(), getRecordKeyName(id)).getKey();
	}

	public Key getChildKey(Class kind, String key) {
		return getChildKeyBuilder(kind, key).getKey();
	}

	public KeyFactory.Builder getChildKeyBuilder(Class kind, String key) {
		return getBaseKeyBuilder().addChild(kind.getSimpleName(), getKeyName(key));
	}

	public String getKeyName(String key) {
		return PREFIX + key;
	}

}
